<template>
  <a-spin
    :loading="loading"
    :size="35"
    class="w-[100%]"
    tip="正在处理, 请稍候..."
  >
    <div class="page-container">
      <!-- 操作按钮区域 -->
      <a-card :bordered="false" class="action-buttons-card mb-6">
        <div class="flex justify-between items-center">
          <div class="flex items-center space-x-2">
            <icon-info-circle class="text-blue-600" />
            <span class="text-sm text-gray-600">请填写完整信息后提交</span>
          </div>
          <a-space>
            <a-button
              type="primary"
              :loading="submitLoading"
              @click="submitForm"
            >
              <template #icon><icon-plus /></template>
              提交申请
            </a-button>
            <a-button @click="goBack">
              <template #icon><icon-arrow-left /></template>
              返回
            </a-button>
          </a-space>
        </div>
      </a-card>

      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        auto-label-width
        layout="vertical"
      >
        <!-- 基本信息区域 -->
        <a-card title="基本信息" :bordered="false" class="form-card">
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item field="projectName" label="项目名称" required>
                <a-input
                  v-model="formData.projectName"
                  allow-clear
                  placeholder="请输入项目名称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="projectAddress" label="项目地址" required>
                <a-input
                  v-model="formData.projectAddress"
                  allow-clear
                  placeholder="请输入项目地址"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="amount" label="补贴申领面积(亩)" required>
                <a-input
                  v-model="formData.amount"
                  placeholder="请输入补贴申领面积"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item field="acceptDate" label="验收时间" required>
                <a-date-picker
                  v-model="formData.acceptDate"
                  style="width: 100%"
                  placeholder="请选择验收时间"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
            <a-col :span="16">
              <!-- 预留字段 -->
            </a-col>
          </a-row>
        </a-card>

        <!-- 项目情况区域 -->
        <a-card title="项目情况" :bordered="false" class="form-card">
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item field="projectDescription" label="情况简介" required>
                <a-textarea
                  v-model="formData.projectDescription"
                  :auto-size="{ minRows: 3, maxRows: 5 }"
                  placeholder="请输入情况简介，体现土地四至以及其他文件批复等"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <!-- 镇街明细区域 -->
        <a-card title="镇街明细" :bordered="false" class="form-card">
          <div
            v-for="(item, index) in formData.subsidyApplicationTownItemList"
            :key="item.id || index"
            class="town-item"
          >
            <a-card size="small" class="town-item-card">
              <template #title>
                <a-space>
                  <icon-location />
                  {{ item.townName }}
                </a-space>
              </template>

              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-item
                    :field="`subsidyApplicationTownItemList.${index}.acceptAcreage`"
                    label="验收亩数"
                    required
                  >
                    <a-input
                      v-model="item.acceptAcreage"
                      placeholder="请输入验收亩数"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item
                    :field="`subsidyApplicationTownItemList.${index}.totalAmount`"
                    label="总金额(万元)"
                    required
                  >
                    <a-input
                      v-model="item.totalAmount"
                      placeholder="请输入总金额"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item
                    :field="`subsidyApplicationTownItemList.${index}.remark`"
                    label="备注"
                  >
                    <a-input v-model="item.remark" placeholder="请输入备注" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-card>
          </div>
        </a-card>

        <!-- 项目文件管理区域 -->
        <a-card title="项目文件管理" :bordered="false" class="form-card">
          <template #extra>
            <a-button type="primary" @click="addUploadArea">
              <template #icon><icon-plus /></template>
              添加附件
            </a-button>
          </template>

          <!-- 多个文件上传区域 -->
          <div
            v-for="(uploadArea, index) in uploadAreas"
            :key="uploadArea.id"
            class="mb-4 p-3 border rounded"
          >
            <div class="mb-3 flex items-center justify-between">
              <span>附件 {{ index + 1 }}</span>
              <a-button
                v-if="uploadAreas.length > 1"
                type="text"
                status="danger"
                @click="removeUploadArea(index)"
              >
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </div>

            <a-form-item label="文件类型" class="mb-3">
              <a-select
                v-model="uploadArea.fileType"
                placeholder="请选择文件类型"
                style="width: 200px"
              >
                <a-option
                  v-for="item in dictData[
                    DICT.lindiSubsidyApplicationFileType
                  ] || []"
                  :key="item.dictKey"
                  :value="String(item.dictKey)"
                >
                  {{ item.dictValue }}
                </a-option>
              </a-select>
            </a-form-item>

            <!-- 文件上传组件 -->
            <div v-if="uploadArea.fileType">
              <uploadFile
                :ref="(el) => setUploadFileRef(el, index)"
                :file-source="getFileSourceByType(uploadArea.fileType)"
                @upload-success="
                  (response) => handleUploadSuccess(response, index)
                "
                :key="`${uploadArea.id}-${uploadArea.fileType}`"
              />
            </div>
          </div>

          <!-- 已有文件展示 -->
          <div v-if="hasExistingFiles">
            <div class="mb-3 font-medium">已上传文件</div>

            <!-- 设计方案文件 -->
            <div v-if="existingDesignSchemeFiles.length > 0" class="mb-3">
              <div class="mb-2 text-sm font-medium">
                {{ getFileTypeDisplayName("0") }}
              </div>
              <div class="space-y-2">
                <div
                  v-for="file in existingDesignSchemeFiles"
                  :key="file.fileId"
                  class="p-3 border rounded flex items-center justify-between"
                >
                  <div class="flex items-center space-x-2">
                    <icon-file :size="20" />
                    <div>
                      <div class="text-sm font-medium truncate">
                        {{ file.fileName }}
                      </div>
                      <div class="text-xs text-gray-500">
                        {{ formatFileSize(file.fileSize) }}
                      </div>
                    </div>
                  </div>
                  <div class="flex space-x-1">
                    <a-button
                      v-perm="['lindi:subsidyApplicationFile:get']"
                      type="text"
                      size="small"
                      @click="previewFile(file)"
                    >
                      <icon-eye />
                    </a-button>
                    <a-button
                      v-perm="['lindi:subsidyApplicationFile:get']"
                      type="text"
                      size="small"
                      @click="downloadFile(file)"
                    >
                      <icon-download />
                    </a-button>
                    <a-button
                      v-perm="['lindi:subsidyApplicationFile:delete']"
                      type="text"
                      size="small"
                      status="danger"
                      @click="removeExistingFile(file, 'designScheme')"
                    >
                      <icon-delete />
                    </a-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 验收意见文件 -->
            <div v-if="existingAcceptanceOpinionFiles.length > 0" class="mb-3">
              <div class="mb-2 text-sm font-medium">
                {{ getFileTypeDisplayName("1") }}
              </div>
              <div class="space-y-2">
                <div
                  v-for="file in existingAcceptanceOpinionFiles"
                  :key="file.fileId"
                  class="p-3 border rounded flex items-center justify-between"
                >
                  <div class="flex items-center space-x-2">
                    <icon-file :size="20" />
                    <div>
                      <div class="text-sm font-medium truncate">
                        {{ file.fileName }}
                      </div>
                      <div class="text-xs text-gray-500">
                        {{ formatFileSize(file.fileSize) }}
                      </div>
                    </div>
                  </div>
                  <div class="flex space-x-1">
                    <a-button
                      v-perm="['lindi:subsidyApplicationFile:get']"
                      type="text"
                      size="small"
                      @click="previewFile(file)"
                    >
                      <icon-eye />
                    </a-button>
                    <a-button
                      v-perm="['lindi:subsidyApplicationFile:get']"
                      type="text"
                      size="small"
                      @click="downloadFile(file)"
                    >
                      <icon-download />
                    </a-button>
                    <a-button
                      v-perm="['lindi:subsidyApplicationFile:delete']"
                      type="text"
                      size="small"
                      status="danger"
                      @click="removeExistingFile(file, 'acceptanceOpinion')"
                    >
                      <icon-delete />
                    </a-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 支付通知文件 -->
            <div v-if="existingPaymentNoticeFiles.length > 0" class="mb-3">
              <div class="mb-2 text-sm font-medium">
                {{ getFileTypeDisplayName("2") }}
              </div>
              <div class="space-y-2">
                <div
                  v-for="file in existingPaymentNoticeFiles"
                  :key="file.fileId"
                  class="p-3 border rounded flex items-center justify-between"
                >
                  <div class="flex items-center space-x-2">
                    <icon-file :size="20" />
                    <div>
                      <div class="text-sm font-medium truncate">
                        {{ file.fileName }}
                      </div>
                      <div class="text-xs text-gray-500">
                        {{ formatFileSize(file.fileSize) }}
                      </div>
                    </div>
                  </div>
                  <div class="flex space-x-1">
                    <a-button
                      v-perm="['lindi:subsidyApplicationPayNotice:get']"
                      type="text"
                      size="small"
                      @click="previewFile(file)"
                    >
                      <icon-eye />
                    </a-button>
                    <a-button
                      v-perm="['lindi:subsidyApplicationPayNotice:get']"
                      type="text"
                      size="small"
                      @click="downloadFile(file)"
                    >
                      <icon-download />
                    </a-button>
                    <a-button
                      v-perm="['lindi:subsidyApplicationPayNotice:delete']"
                      type="text"
                      size="small"
                      status="danger"
                      @click="removeExistingFile(file, 'paymentNotice')"
                    >
                      <icon-delete />
                    </a-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 付款记录文件 -->
            <div v-if="existingPaymentRecordFiles.length > 0" class="mb-3">
              <div class="mb-2 text-sm font-medium">
                {{ getFileTypeDisplayName("3") }}
              </div>
              <div class="space-y-2">
                <div
                  v-for="file in existingPaymentRecordFiles"
                  :key="file.fileId"
                  class="p-3 border rounded flex items-center justify-between"
                >
                  <div class="flex items-center space-x-2">
                    <icon-file :size="20" />
                    <div>
                      <div class="text-sm font-medium truncate">
                        {{ file.fileName }}
                      </div>
                      <div class="text-xs text-gray-500">
                        {{ formatFileSize(file.fileSize) }}
                      </div>
                    </div>
                  </div>
                  <div class="flex space-x-1">
                    <a-button
                      v-perm="['lindi:subsidyApplicationPayRecord:get']"
                      type="text"
                      size="small"
                      @click="previewFile(file)"
                    >
                      <icon-eye />
                    </a-button>
                    <a-button
                      v-perm="['lindi:subsidyApplicationPayRecord:get']"
                      type="text"
                      size="small"
                      @click="downloadFile(file)"
                    >
                      <icon-download />
                    </a-button>
                    <a-button
                      v-perm="['lindi:subsidyApplicationPayRecord:delete']"
                      type="text"
                      size="small"
                      status="danger"
                      @click="removeExistingFile(file, 'paymentRecord')"
                    >
                      <icon-delete />
                    </a-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </a-form>
    </div>
  </a-spin>
</template>

<script setup>
import {
  defineEmits,
  defineProps,
  computed,
  getCurrentInstance,
  onMounted,
  reactive,
  ref,
} from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import {
  IconArrowLeft,
  IconDelete,
  IconDownload,
  IconEye,
  IconFile,
  IconFilePdf,
  IconInfoCircle,
  IconLocation,
  IconPlus,
} from "@arco-design/web-vue/es/icon";
// 导入API方法
import {
  getSubsidyApplicationBySubsidyApplicationIdApi,
  addSubsidyApplicationApi,
  updateSubsidyApplicationBySubsidyApplicationIdApi,
  deleteSubsidyApplicationFileByFileIdApi,
} from "~/api/lindi/subsidyApplication.js";
import uploadFile from "~/components/uploadFile/index.vue";
import { fileSource } from "~/utils/sys.js";
import { deleteFileApi } from "~/api/basic/file.js";
import { DICT, LoadDicts } from "~/utils/dict.js";

// 定义props
const props = defineProps({
  subsidyApplicationId: {
    type: String,
    default: "",
  },
});

// 定义事件
const emit = defineEmits(["cancel", "ok"]);

// 全局实例
const { proxy } = getCurrentInstance();

// 加载状态
const loading = ref(false);
const submitLoading = ref(false);

// 表单引用
const formRef = ref(null);

// 已有文件列表
const existingDesignSchemeFiles = ref([]);
const existingAcceptanceOpinionFiles = ref([]);
const existingPaymentNoticeFiles = ref([]);
const existingPaymentRecordFiles = ref([]);

// 多个上传区域管理
const uploadAreas = ref([
  {
    id: Date.now(),
    fileType: "",
  },
]);

// 加载字典数据
const dictData = proxy.LoadDicts([DICT.lindiSubsidyApplicationFileType]);

// 上传组件引用数组
const uploadFileRefs = ref([]);

// 跟踪新上传的文件ID，用于取消时清理
const newUploadedFileIds = ref([]);

// 文件源配置
const fileSourceConfig = {
  designScheme: fileSource.lindi_subsidy_design?.key,
  acceptanceOpinion: fileSource.lindi_subsidy_acceptance?.key,
  paymentNotice: fileSource.lindi_subsidy_payment?.key,
  paymentRecord: fileSource.lindi_subsidy_payment_record?.key,
};

// 计算属性：是否有已存在的文件
const hasExistingFiles = computed(() => {
  return (
    existingDesignSchemeFiles.value.length > 0 ||
    existingAcceptanceOpinionFiles.value.length > 0 ||
    existingPaymentNoticeFiles.value.length > 0 ||
    existingPaymentRecordFiles.value.length > 0
  );
});

// 根据文件类型获取文件源
const getFileSourceByType = (fileType) => {
  return fileSourceConfig[fileType];
};

// 根据文件类型获取字典显示名称
const getFileTypeDisplayName = (fileType) => {
  const fileTypeDict = dictData[DICT.lindiSubsidyApplicationFileType] || [];
  const item = fileTypeDict.find(
    (dict) => String(dict.dictKey) === String(fileType)
  );
  return item ? item.dictValue : fileType;
};

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size || size === 0) return "0 B";

  const units = ["B", "KB", "MB", "GB", "TB"];
  const bytes = parseInt(size);

  if (bytes === 0) return "0 B";

  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  const formattedSize = (bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1);

  return `${formattedSize} ${units[i]}`;
};

// 添加上传区域
const addUploadArea = () => {
  uploadAreas.value.push({
    id: Date.now(),
    fileType: "",
  });
};

// 删除上传区域
const removeUploadArea = (index) => {
  if (uploadAreas.value.length > 1) {
    uploadAreas.value.splice(index, 1);
    uploadFileRefs.value.splice(index, 1);
  }
};

// 设置上传组件引用
const setUploadFileRef = (el, index) => {
  if (el) {
    uploadFileRefs.value[index] = el;
  }
};

// 表单数据
const formData = reactive({
  subsidyApplicationId: "",
  projectName: "",
  projectAddress: "",
  amount: "",
  acceptDate: "",
  projectDescription: "",
  subsidyApplicationFileList: [],
  subsidyApplicationTownItemList: [
    // 青阳街道
    { townName: "青阳街道", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 梅岭街道
    { townName: "梅岭街道", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 新塘街道
    { townName: "新塘街道", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 罗山街道
    { townName: "罗山街道", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 灵源街道
    { townName: "灵源街道", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 永和镇
    { townName: "永和镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 安海镇
    { townName: "安海镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 东石镇
    { townName: "东石镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 英林镇
    { townName: "英林镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 金井镇
    { townName: "金井镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 龙湖镇
    { townName: "龙湖镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 深沪镇
    { townName: "深沪镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 西园街道
    { townName: "西园街道", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 池店镇
    { townName: "池店镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 陈埭镇
    { townName: "陈埭镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 紫帽镇
    { townName: "紫帽镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 内坑镇
    { townName: "内坑镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 西滨镇
    { townName: "西滨镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
    // 磁灶镇
    { townName: "磁灶镇", acceptAcreage: "0", totalAmount: "0", remark: "" },
  ],
  remark: "",
});

// 表单规则
const rules = {
  projectName: [
    { required: true, message: "请输入项目名称" },
    { maxLength: 100, message: "项目名称长度不能超过100个字符" },
  ],
  projectAddress: [
    { required: true, message: "请输入项目地址" },
    { maxLength: 200, message: "项目地址长度不能超过200个字符" },
  ],
  amount: [{ required: true, message: "请输入补贴申领面积" }],
  acceptDate: [{ required: true, message: "请选择验收时间" }],
  projectDescription: [{ required: true, message: "请输入情况简介" }],
  // 镇街明细验证规则
  "subsidyApplicationTownItemList.*.townName": [
    { required: true, message: "请输入镇街名称" },
  ],
  "subsidyApplicationTownItemList.*.acceptAcreage": [
    { required: true, message: "请输入验收亩数" },
  ],
  "subsidyApplicationTownItemList.*.totalAmount": [
    { required: true, message: "请输入总金额" },
  ],
};

// 返回列表页
const goBack = () => {
  cleanupUnusedFiles()
    .then(() => {
      emit("cancel");
    })
    .catch((error) => {
      console.error("清理文件失败:", error);
      emit("cancel"); // 即使清理失败也要返回
    });
};

// 获取补贴申请详情
const getSubsidyDetail = () => {
  if (!props.subsidyApplicationId) {
    return;
  }
  loading.value = true;

  getSubsidyApplicationBySubsidyApplicationIdApi(props.subsidyApplicationId)
    .then((res) => {
      console.log("获取补贴申请详情成功:", res);

      // 处理文件列表
      if (
        res.subsidyApplicationFileList &&
        res.subsidyApplicationFileList.length > 0
      ) {
        // 根据文件类型分类处理，将file对象合并到文件信息中
        existingDesignSchemeFiles.value =
          res.subsidyApplicationFileList
            .filter((item) => item.fileType === "0")
            .map((item) => ({
              ...item.file,
              fileType: item.fileType,
              subsidyApplicationFileId: item.id,
            })) || [];

        existingAcceptanceOpinionFiles.value =
          res.subsidyApplicationFileList
            .filter((item) => item.fileType === "1")
            .map((item) => ({
              ...item.file,
              fileType: item.fileType,
              subsidyApplicationFileId: item.id,
            })) || [];

        existingPaymentNoticeFiles.value =
          res.subsidyApplicationFileList
            .filter((item) => item.fileType === "2")
            .map((item) => ({
              ...item.file,
              fileType: item.fileType,
              subsidyApplicationFileId: item.id,
            })) || [];

        existingPaymentRecordFiles.value =
          res.subsidyApplicationFileList
            .filter((item) => item.fileType === "3")
            .map((item) => ({
              ...item.file,
              fileType: item.fileType,
              subsidyApplicationFileId: item.id,
            })) || [];
      } else {
        existingDesignSchemeFiles.value = [];
        existingAcceptanceOpinionFiles.value = [];
        existingPaymentNoticeFiles.value = [];
        existingPaymentRecordFiles.value = [];
      }

      Object.assign(formData, res);

      // 如果没有镇街明细项，则初始化所有镇街
      if (
        !formData.subsidyApplicationTownItemList ||
        formData.subsidyApplicationTownItemList.length === 0
      ) {
        formData.subsidyApplicationTownItemList = [
          {
            townName: "青阳街道",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "梅岭街道",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "新塘街道",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "罗山街道",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "灵源街道",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "永和镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "安海镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "东石镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "英林镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "金井镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "龙湖镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "深沪镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "西园街道",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "池店镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "陈埭镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "紫帽镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "内坑镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "西滨镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
          {
            townName: "磁灶镇",
            acceptAcreage: "0",
            totalAmount: "0",
            remark: "",
          },
        ];
      }
    })
    .catch((error) => {
      console.error("获取补贴申请详情失败:", error);
      Message.error("获取详情失败，请稍后重试");
    })
    .finally(() => {
      loading.value = false;
    });
};

// 提交表单
const submitForm = () => {
  formRef.value
    .validate()
    .then((valid) => {
      if (valid) {
        return Promise.reject("表单验证失败");
      }

      submitLoading.value = true;

      // 创建提交数据的副本
      const submitData = { ...formData };

      // 构建subsidyApplicationFileList
      const subsidyApplicationFileList = [];

      // 添加现有文件
      existingDesignSchemeFiles.value.forEach((file) => {
        subsidyApplicationFileList.push({
          subsidyApplicationId: props.subsidyApplicationId || "",
          fileId: file.fileId,
          fileType: file.fileType || "0",
        });
      });

      existingAcceptanceOpinionFiles.value.forEach((file) => {
        subsidyApplicationFileList.push({
          subsidyApplicationId: props.subsidyApplicationId || "",
          fileId: file.fileId,
          fileType: file.fileType || "1",
        });
      });

      existingPaymentNoticeFiles.value.forEach((file) => {
        subsidyApplicationFileList.push({
          subsidyApplicationId: props.subsidyApplicationId || "",
          fileId: file.fileId,
          fileType: file.fileType || "2",
        });
      });

      existingPaymentRecordFiles.value.forEach((file) => {
        subsidyApplicationFileList.push({
          subsidyApplicationId: props.subsidyApplicationId || "",
          fileId: file.fileId,
          fileType: file.fileType || "3",
        });
      });

      // 添加新上传的文件
      uploadFileRefs.value.forEach((ref, index) => {
        if (ref?.getUploadFileId() && uploadAreas.value[index]?.fileType) {
          subsidyApplicationFileList.push({
            subsidyApplicationId: props.subsidyApplicationId || "",
            fileId: ref.getUploadFileId(),
            fileType: uploadAreas.value[index].fileType,
          });
        }
      });

      submitData.subsidyApplicationFileList = subsidyApplicationFileList;

      if (props.subsidyApplicationId) {
        // 编辑模式
        return updateSubsidyApplicationBySubsidyApplicationIdApi(submitData);
      } else {
        // 新增模式
        return addSubsidyApplicationApi(submitData);
      }
    })
    .then((res) => {
      Message.success("保存成功");
      newUploadedFileIds.value = []; // 清理文件ID列表
      emit("ok");
    })
    .catch((error) => {
      console.error("保存补贴申请失败:", error);
      if (error !== "表单验证失败") {
        Message.error("保存失败，请稍后重试");
      }
    })
    .finally(() => {
      submitLoading.value = false;
    });
};

// 下载文件
const downloadFile = (file) => {
  if (file.fileUrl) {
    const link = document.createElement("a");
    link.href = file.fileUrl;
    link.download = file.fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    Message.error("文件下载链接不存在");
  }
};

// 预览文件
const previewFile = (file) => {
  if (file.fileUrl) {
    window.open(file.fileUrl, "_blank");
  } else {
    Message.error("文件预览链接不存在");
  }
};

// 删除已有文件
const removeExistingFile = (file, fileType) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除文件【${file.fileName}】吗？`,
    onOk: () => {
      deleteSubsidyApplicationFileByFileIdApi(file.fileId)
        .then((res) => {
          // 检查响应状态
          if (res && res.code === 200) {
            // 根据文件类型删除对应的文件
            if (fileType === "designScheme") {
              existingDesignSchemeFiles.value =
                existingDesignSchemeFiles.value.filter(
                  (f) => f.fileId !== file.fileId
                );
            } else if (fileType === "acceptanceOpinion") {
              existingAcceptanceOpinionFiles.value =
                existingAcceptanceOpinionFiles.value.filter(
                  (f) => f.fileId !== file.fileId
                );
            } else if (fileType === "paymentNotice") {
              existingPaymentNoticeFiles.value =
                existingPaymentNoticeFiles.value.filter(
                  (f) => f.fileId !== file.fileId
                );
            } else if (fileType === "paymentRecord") {
              existingPaymentRecordFiles.value =
                existingPaymentRecordFiles.value.filter(
                  (f) => f.fileId !== file.fileId
                );
            }
            Message.success("文件删除成功");
          } else {
            console.error("删除文件失败:", res);
            Message.error(res?.message || "文件删除失败，请稍后重试");
          }
        })
        .catch((error) => {
          console.error("删除文件失败:", error);
          const errorMessage =
            error?.response?.data?.message ||
            error?.message ||
            "文件删除失败，请稍后重试";
          Message.error(errorMessage);
        });
    },
  });
};

// 添加镇街明细项
const addTownItemItem = () => {
  formData.subsidyApplicationTownItemList.push({
    townName: "",
    acceptAcreage: "",
    totalAmount: "",
    remark: "",
  });
};

// 删除镇街明细项
const removeTownItemItem = (index) => {
  if (formData.subsidyApplicationTownItemList.length > 1) {
    formData.subsidyApplicationTownItemList.splice(index, 1);
  }
};

// 清理未使用的文件
const cleanupUnusedFiles = () => {
  const deletePromises = newUploadedFileIds.value.map((fileId) => {
    return deleteFileApi(fileId).catch((error) => {
      console.error("删除文件失败:", error);
      return null; // 返回null表示删除失败，但不中断整个流程
    });
  });

  return Promise.all(deletePromises).then(() => {
    newUploadedFileIds.value = [];
  });
};

// 处理文件上传成功
const handleUploadSuccess = (response, index) => {
  if (response && response.fileId && !props.subsidyApplicationId) {
    newUploadedFileIds.value.push(response.fileId);
  }
  console.log(`上传区域 ${index + 1} 文件上传成功:`, response);
};

// 组件挂载时初始化
onMounted(() => {
  getSubsidyDetail();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f7f8fa;
  min-height: calc(100vh - 60px);
}

.form-card {
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-buttons-card {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.town-item {
  margin-bottom: 16px;
}

.town-item:last-child {
  margin-bottom: 0;
}

.town-item-card {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.town-item-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.edit-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.top-bar {
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-container {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.file-upload-section {
  margin-bottom: 32px;
  padding: 20px;
  background-color: #fafbfc;
  border-radius: 8px;
  border: 1px solid #e5e6eb;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e5e6eb;
  padding-bottom: 12px;
}

.upload-area-item {
  padding: 16px;
  border: 1px solid #e5e6eb;
  border-radius: 6px;
  background-color: #ffffff;
  margin-bottom: 16px;
}

.upload-area-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.upload-area-title {
  font-weight: 500;
  color: #1d2129;
  font-size: 14px;
}

.existing-files-container {
  background: white;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #e5e6eb;
}

.file-item-card {
  transition: all 0.3s ease;
}

.file-item-card:hover {
  transform: translateY(-2px);
}

.file-card {
  border: 1px solid #e5e6eb;
  transition: all 0.3s ease;
}

.file-card:hover {
  border-color: #165dff;
  box-shadow: 0 4px 12px rgba(22, 93, 255, 0.15);
}

.mb-2 {
  margin-bottom: 8px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mb-6 {
  margin-bottom: 24px;
}

.mb-3 {
  margin-bottom: 12px;
}

.mb-0 {
  margin-bottom: 0;
}

.mr-2 {
  margin-right: 8px;
}

.p-3 {
  padding: 12px;
}

.border {
  border: 1px solid #e5e7eb;
}

.rounded {
  border-radius: 6px;
}

.text-lg {
  font-size: 18px;
}

.text-sm {
  font-size: 14px;
}

.text-xs {
  font-size: 12px;
}

.font-medium {
  font-weight: 500;
}

.text-gray-800 {
  color: #1d2129;
}

.text-gray-700 {
  color: #4e5969;
}

.text-gray-900 {
  color: #1d2129;
}

.text-gray-500 {
  color: #86909c;
}

.text-green-500 {
  color: #00b42a;
}

.text-blue-600 {
  color: #165dff;
}

.text-red-600 {
  color: #f53f3f;
}

.text-gray-600 {
  color: #6b7280;
}

.bg-gray-100 {
  background-color: #f7f8fa;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.items-start {
  align-items: flex-start;
}

.justify-between {
  justify-content: space-between;
}

.space-x-1 > * + * {
  margin-left: 4px;
}

.space-x-2 > * + * {
  margin-left: 8px;
}

.text-blue-600 {
  color: #165dff;
}

.text-gray-600 {
  color: #6b7280;
}

.space-x-3 > * + * {
  margin-left: 12px;
}

.space-y-2 > * + * {
  margin-top: 8px;
}

.flex-shrink-0 {
  flex-shrink: 0;
}

.flex-1 {
  flex: 1;
}

.min-w-0 {
  min-width: 0;
}

.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.mt-6 {
  margin-top: 24px;
}

.mb-6 {
  margin-bottom: 24px;
}

.justify-center {
  justify-content: center;
}

.flex-wrap {
  flex-wrap: wrap;
}

.gap-2 {
  gap: 8px;
}

.grid {
  display: grid;
}

.grid-cols-1 {
  grid-template-columns: repeat(1, minmax(0, 1fr));
}

.gap-4 {
  gap: 16px;
}

.h-full {
  height: 100%;
}

@media (min-width: 768px) {
  .md\:grid-cols-2 {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
/* 镇街明细样式 */
.town-payment-section {
  margin: 24px 0;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.town-payment-item {
  transition: all 0.3s ease;
}

.town-payment-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.town-payment-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 8px;
  border-bottom: 1px solid #e5e6eb;
}

.empty-state {
  padding: 40px;
  text-align: center;
  background-color: #fafafa;
  border-radius: 8px;
  border: 2px dashed #d9d9d9;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .town-payment-item .arco-col {
    margin-bottom: 16px;
  }
}
</style>
